package arithmetic.leetCode;

import arithmetic.leetCode.ds.ListNode;

/**
 * @author dycong
 * @date 2019/9/14 12:26
 * <p>
 * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
 * Output: 7 -> 0 -> 8
 * Explanation: 342 + 465 = 807.
 */
public class TwoSum_2 {

    public static void main(String[] args) {
        ListNode two = new ListNode(2);
        ListNode four = new ListNode(4);
        ListNode three = new ListNode(3);
        two.next = four;
        four.next = three;

        ListNode five = new ListNode(5);
        ListNode six = new ListNode(6);
        ListNode four_ = new ListNode(4);
        five.next = six;
        six.next = four_;
        ListNode root = addTwoNumbers(two, five);
        while (root != null) {
            System.out.println(root.val);
            root = root.next;
        }
    }


    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (null == l1 && null == l2) {
            return null;
        }
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        //定义 head tail 言简意赅，也方便逻辑处理
        ListNode head = null;
        ListNode tail = null;
        int remainder = 0;
        while (l1 != null || l2 != null || remainder > 0) {
            int curValue = remainder;

            if (l1 != null) {
                curValue += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                curValue += l2.val;
                l2 = l2.next;
            }
            //余数
            remainder = curValue / 10;

            ListNode node = new ListNode(curValue % 10);
            if (head == null) {
                head = node;
                tail = node;
            } else {
                tail.next = node;
                tail = tail.next;
            }
        }
        return head;
    }
}
